package com.tools.seckillgoods;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.login.R;
import com.tools.CommonThings;
import com.tools.CountDownTimer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public class SecKillGoodsAdapter extends ArrayAdapter<SecKillGoods> {
    private final int resourceId;
    private Context mContext;
    private TextView goodsName, secRate, secPrice, secRisk;
    private TextView stateText, dayText, dayTian; //状态（距离秒杀。。。），天数，汉字（天）
    private CountDownTimer countDownTimer;
    private long countTime;

    public SecKillGoodsAdapter(Context context, int resource, List<SecKillGoods> objects) {
        super(context, resource, objects);
        resourceId = resource;
        mContext = context;
    }

    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if(convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(resourceId,null);
        }

        SecKillGoods secKillGoods = getItem(position);
        dayTian = convertView.findViewById(R.id.seckill_time_day_text);
        goodsName = convertView.findViewById(R.id.secKill_name);
        secRate = convertView.findViewById(R.id.secKill_rate);
        secPrice = convertView.findViewById(R.id.secKill_price);
        secRisk = convertView.findViewById(R.id.secKill_risk_grade);
        stateText = convertView.findViewById(R.id.seckill_time_state);
        dayText = convertView.findViewById(R.id.seckill_time_day);
        countDownTimer = convertView.findViewById(R.id.seckill_time_count_timer);

        goodsName.setText(secKillGoods.getName());
        secRate.setText(CommonThings.invertPercent(secKillGoods.getAnnualInterestRate()));
        secPrice.setText(String.format(mContext.getResources().getString(R.string.secKill_price), secKillGoods.getSecKillPrice()));

        if (secKillGoods.getRiskGrade() == 0){
            secRisk.setText("低风险");
            secRisk.setBackgroundResource(R.drawable.bg_risk_safe);
        }else if (secKillGoods.getRiskGrade() == 1){
            secRisk.setText("中风险");
            secRisk.setBackgroundResource(R.drawable.bg_risk_warn);
        }else if (secKillGoods.getRiskGrade() == 2){
            secRisk.setText("高风险");
            secRisk.setBackgroundResource(R.drawable.bg_risk_danger);
        }


        try {
            countTime = setCountdown(secKillGoods.getStartDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (countTime > 0){ //大于0表示秒杀还未开始
            // 86400000 是一天24小时毫秒数
            dayText.setText(String.valueOf(countTime / 86400000));
            countDownTimer.init(countTime % 86400000, 1000);
            countDownTimer.updateTimer();
        }else if (countTime < 0){
            try {
                countTime = setCountdown(secKillGoods.getEndDate());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            countTime = Math.abs(countTime);
            stateText.setText("距离活动结束还有");
            dayText.setText(String.valueOf(countTime / 86400000));
            countDownTimer.init(countTime % 86400000, 1000);
            countDownTimer.updateTimer();
        }

        while (countDownTimer.isEnd){
            int day = Integer.parseInt(dayText.getText().toString());
            if (day > 0){
                day -= 1;
                dayText.setText(String.valueOf(day));
                countDownTimer.init(86400000, 1000);
                countDownTimer.updateTimer();
            }else {
                stateText.setText("秒杀已结束");
                dayText.setVisibility(View.GONE);
                dayTian.setVisibility(View.GONE);
                countDownTimer.setVisibility(View.GONE);
            }
        }

        return convertView;
    }

    //开始时间与系统时间之间的差（开始时间-系统时间）
    private long setCountdown(String startDate) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        long NTime = simpleDateFormat.parse(simpleDateFormat.format(date)).getTime();
        long OTime = simpleDateFormat.parse(startDate).getTime();
        return (OTime - NTime);
    }
}
